package com.offcn.seckill.thread;

import com.offcn.seckill.dao.SeckillGoodsMapper;
import com.offcn.seckill.pojo.SeckillGoods;
import com.offcn.seckill.pojo.SeckillOrder;
import com.offcn.seckill.pojo.SeckillStatus;
import com.offcn.utils.IdWorker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class MutilThreadCreateOrder {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired(required = false)
    private SeckillGoodsMapper goodsMapper;

    /**
     * 线程安全的问题是什么原因导致的？
     * 内存的值的问题，解决线程安全问题 不从栈内存和堆内存中获取数据 ，从数据源中获取数据
     */
    @Async
    public void createOrder(){
        // 右出
        SeckillStatus seckillStatus = (SeckillStatus)redisTemplate.boundListOps("seckillOrderQueue").rightPop();
        String timer = seckillStatus.getTimer();
        Long id = seckillStatus.getGoodsId();
        String username = seckillStatus.getUsername();

        // 避免出现超卖的情况
        Long[] ids = (Long[])redisTemplate.boundListOps("seckillGoodsCountList_" + id).rightPop();
        if (ids == null || ids.length == 0){
            // 库存没有了
            redisTemplate.boundHashOps("UserQueueStatus").delete(username); // 没有抢购到的用户删除抢单信息
            redisTemplate.boundHashOps("UserQueueCount").delete(username);  // 已经抢购的用户也删除抢单信息
            return ; // 结束运行
        }

        System.out.println("抢单开始....");
        SeckillGoods seckillGoods = (SeckillGoods) redisTemplate.boundHashOps("seckillGoods_" + timer).get(id);
        if (seckillGoods == null || seckillGoods.getStockCount() <= 0) {
            throw new RuntimeException("商品已经售罄");
        }
        // 创建订单对象
        SeckillOrder order = new SeckillOrder();
        long orderId = new IdWorker(2, 1).nextId();
        order.setId(orderId);
        order.setSeckillId(id);
        order.setMoney(seckillGoods.getCostPrice()); // 实际价格 限购1个商品
        order.setUserId(username);
        order.setCreateTime(new Date());
        order.setStatus("0");  // 未支付
        // 存储订单数据到redis 中
        redisTemplate.boundHashOps("seckillOrder").put(username, order);
        // 减库存
        /*seckillGoods.setStockCount(seckillGoods.getStockCount() - 1);*/
        Long stockCount = redisTemplate.boundHashOps("seckillGoodsCount").increment(id, -1);

        // 判断库存是否为空，如果为空记录到数据库，表示该商品已经售罄
        /*if (seckillGoods.getStockCount().equals(0)) {*/
        if (stockCount <= 0) {
            goodsMapper.updateById(seckillGoods);
            // 清除redis中该数据的数据
            redisTemplate.boundHashOps("seckillGoods_" + timer).delete(id);
        } else {
            redisTemplate.boundHashOps("seckillGoods_" + timer).put(id, seckillGoods);
        }
        System.out.println("抢单结束");

        System.out.println("抢单结束");

    }
}
